package com.aqie.arithmetic.array;

import java.util.Arrays;

/**
 * 数组操作  二分查找 递归实现
 */
public class MyArray {
    /**
     * 1，数组翻转
     * 核心 交换 arr[i] = arr[N-1-i];
     * @param arr
     */
    public static void reverseArray(double[] arr){
        int N = arr.length;
        for (int i = 0; i < N / 2;i++){
            double tmp = arr[i];
            arr[i] = arr[N-1-i];
            arr[N-i-1] = tmp;
        }
        System.out.println(Arrays.toString(arr));
    }

    /**
     * 2，矩阵相乘
     */
    public static double[][] matrixMultiplication(double[][] a, double[][] b){
       int N = a.length;
       double[][] c = new double[N][N];
       for (int i = 0; i < N; i++){
           for (int j = 0; j < N; j++){
               // 计算行i 和 列 j 的点乘
               for (int k = 0; k < N; k++){
                   c[i][j] += a[i][k] * b[k][j];
               }
           }
       }
       return c;
    }

    /**
     * 3, 二分查找递归实现, 必须是升序数组
     * @param a
     */
    public static int binarySearch(int key, double[] a){
        return rank(key, a, 0, a.length - 1);
    }

    private static int rank(int key, double[] a, int l, int r) {
        // key 的索引 在l r 之间
        if (l > r) return -1;
        int mid = l + (r - l) / 2;
        if(key < a[mid]){
            return rank(key, a, l, mid - 1);
        }else if (key > a[mid]){
            return rank(key, a, mid + 1, r);
        }else {
            return mid;
        }

    }

    public static void main(String[] args) {
        double[] arr = {1,2,3};
        // reverseArray(arr);

        double[][] a = {{1,2,3},{4,5,6}, {7,8,9}}, b = {{1,2,3},{4,5,6}, {7,8,9}};
        System.out.println(Arrays.deepToString(matrixMultiplication(a, b)));

        // 两个变量指向同一个内存区域
        int[] a1 = {1,2,3};
        int[] b1 = a1;
        b1[1] = 4;
        System.out.println(Arrays.toString(a1));

        int key = 3;
        System.out.println(binarySearch(key, arr));

    }
}
